package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver = null;

    public static WebDriver createWebdriver() {
        if(driver == null) {
            //使⽤插件管理⼯具webdrivermanager
            WebDriverManager.chromedriver().setup();
            //配置浏览器配置
            ChromeOptions options = new ChromeOptions();
            //1)允许任何来源的远程连接
            options.addArguments("--remote-allow-origins=*");
            //2)增加无头模式
            //options.addArguments("-headless");
            //创建浏览器驱动对象
            driver = new ChromeDriver(options);
            //定义一个隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }
    public Utils(String url) {
        driver = createWebdriver();
        driver.get(url);
    }
    public void getScreenShot(String str) throws IOException {
        createWebdriver();
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HH-mm-ss-SS");
        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());
        //  ./src/test/java/image/日期文件夹/方法时间的图片
        String fileName = "./src/test/image/" + dirTime + "/" + str + fileTime + ".png";
        File file = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(file,new File(fileName));
        driver.close();
    }
    public static void solveAlertAccept() {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3));
        Alert alert = wait.until(ExpectedConditions.alertIsPresent());
        alert.accept();
    }
    public static void solveAlertDismiss() {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3));
        Alert alert = wait.until(ExpectedConditions.alertIsPresent());
        alert.dismiss();
    }
}
